package com.wephone.Student.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TreeSet;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.wephone.Student.R;

import com.wephone.Student.bean.BaseResponse;
import com.wephone.Student.bean.GroupInfoDetailResponse;
import com.wephone.Student.bean.GroupResponse;
import com.wephone.Student.bean.data.GroupInfo;
import com.wephone.Student.bean.data.MyLocationInfo;
import com.wephone.Student.bean.data.UserInfoData;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.RoundImageView;
import com.wephone.Student.util.Util;


public class GroupMembersActivity extends BaseActivity {
	private GroupInfo groupData;
	private ArrayList<UserInfoData> users = new ArrayList<UserInfoData>();//群成员列表
	
	private ArrayList<UserInfoData> admins = new ArrayList<UserInfoData>();//群主/可能有多个
	private ListView group_list;
	private GroupViewAdapter adapter;
	private TreeSet<Integer> sectionHeader = new TreeSet<Integer>();
	
	//获取详情
	private MyResponseHandler getHandler(){
		MyResponseHandler handler = new MyResponseHandler(GroupMembersActivity.this,GroupInfoDetailResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					Object data = ((GroupInfoDetailResponse)response).getData();
					Gson gson = new Gson();
					try {
						String string = gson.toJson(data);
						JSONArray users_Json = new JSONArray(string);
						for (int i = 0; i < users_Json.length(); i++) {
							JSONObject obj = users_Json.getJSONObject(i);
							JSONObject uinfo = obj.getJSONObject("uinfo");
							UserInfoData userInfoData = (UserInfoData)gson.fromJson(uinfo.toString(), UserInfoData.class);
							if(groupData.getUid() == userInfoData.getuId()){
								admins.add(userInfoData);
							}else{
								users.add(userInfoData);
							}
						}
						int length = users.size();
						for(int i=0;i<admins.size();i++){
							users.add(0, admins.get(i));
						}
						UserInfoData userInfoData = new UserInfoData();
						userInfoData.setuName("群主");
						userInfoData.setuAge("0");
						users.add(0,userInfoData);
						
						UserInfoData userInfoData2 = new UserInfoData();
						userInfoData2.setuName("群成员");
						userInfoData2.setuAge((length-1)+"人");
						users.add(2,userInfoData2);
						if(users.size()>0){
							for(int i=0;i<users.size();i++){
								if(i>9){
									break;
								}
								UserInfoData userData = (UserInfoData) users.get(i);
								ImageView img = new ImageView(getApplicationContext());
						        LinearLayout.LayoutParams viewParamsCenter = new LinearLayout.LayoutParams(
						                (int)Util.convertDpToPixel(16, getApplicationContext()), (int)Util.convertDpToPixel(16, getApplicationContext()));
						        viewParamsCenter.leftMargin=(int)Util.convertDpToPixel(5, getApplicationContext());
						        img.setImageResource(R.drawable.ic_launcher);
						        img.setLayoutParams(viewParamsCenter);
						       
						        imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+userData.getuIcon(), img);
							}
							adapter.notifyDataSetChanged();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		};
		return handler;
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group_members);
		
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null){
			groupData = (GroupInfo)bundle.getSerializable("groupData");
			init();
		}else{
			finish();
			Toast.makeText(getApplicationContext(), "数据异常", Toast.LENGTH_SHORT).show();
		}
	}
	
	private void init(){
		
		group_list = (ListView)findViewById(R.id.group_list);
		
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		sectionHeader.add(0);
		sectionHeader.add(2);
		adapter = new GroupViewAdapter();
		group_list.setAdapter(adapter);
		group_list.setOnItemClickListener(new ListView.OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Bundle bundle = new Bundle();
				bundle.putSerializable("userData", users.get(arg2));
				startActivity(new Intent(getApplicationContext(),UserInfoDetailActivity.class).putExtras(bundle));
			}});
		
		if(!TextUtils.isEmpty(groupData.getPic())){
			DisplayImageOptions options = new DisplayImageOptions.Builder()
	        .showStubImage(R.drawable.default_user_logo)
	        .showImageOnFail(R.drawable.default_user_logo)
	        .bitmapConfig(Bitmap.Config.ARGB_8888)
	        .cacheInMemory()
	        .cacheOnDisc()
//	        .displayer(new RoundedBitmapDisplayer(1000))
	        .build();
//			imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+userData.getuIcon(), itemImage, options);
		}
		//获取群组成员
		RequestParams params2 = new RequestParams();
		params2.put("groupid", groupData.getGroupid());
		HttpClient.getInstance().get(Constants.API_GET_CHART_USERS, params2, getHandler());
	}	
	private DisplayImageOptions options = new DisplayImageOptions.Builder()
    .showStubImage(R.drawable.liuxuequan_image_default)
    .showImageOnFail(R.drawable.liuxuequan_image_default)
    .bitmapConfig(Bitmap.Config.ARGB_8888)
    .cacheInMemory()
    .cacheOnDisc()
//    .displayer(new RoundedBitmapDisplayer(1000))
    .build();
	
	private class GroupViewAdapter extends BaseAdapter{
		private static final int TYPE_ITEM = 0;
		private static final int TYPE_SEPARATOR = 1;
		
		@Override
		public int getCount() {
			return users.size();
		}

		@Override
		public int getItemViewType(int position) {
			return sectionHeader.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
		}

		@Override
		public int getViewTypeCount() {
			return 2;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			int rowType = getItemViewType(position);
			if(rowType == TYPE_ITEM){
					if(convertView==null){
						convertView = getLayoutInflater().inflate(R.layout.include_goup_member_list_item, null);
					}
					UserInfoData userData = users.get(position);
					
					TextView itemName = (TextView)convertView.findViewById(R.id.item_name);
					itemName.setText(userData.getuName());
					TextView itemSign = (TextView)convertView.findViewById(R.id.item_signature);
					itemSign.setText(userData.getuSign());
					
					
					RoundImageView itemImage = (RoundImageView)convertView.findViewById(R.id.item_image);
					if(!TextUtils.isEmpty(userData.getuIcon())){
						String endStr = userData.getuIcon().substring(userData.getuIcon().lastIndexOf("."));
						imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+userData.getuIcon().replace(endStr, "_150_150"+endStr), itemImage, options);
		//				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+userData.getuIcon(), itemImage, options);
					}else{
						itemImage.setImageResource(R.drawable.default_user_logo);
					}
			}else{
				if(convertView==null){
					convertView = getLayoutInflater().inflate(R.layout.include_group_member_header, null);
				}
				UserInfoData userData = users.get(position);
				TextView groupName = (TextView)convertView.findViewById(R.id.groupName);
				groupName.setText(userData.getuName());
				
				TextView groupNum = (TextView)convertView.findViewById(R.id.groupNum);
				if(userData.getuAge().equals("0")){
					groupNum.setVisibility(View.GONE);
				}else{
					groupNum.setText(userData.getuAge());
					groupNum.setVisibility(View.VISIBLE);
				}
			}
			return convertView;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return users.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}
	}
}
